﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.SharePoint;
using System;
using System.Linq;

namespace SP.Exporters.Extractors
{
    public class FieldUrlExtractor : IFieldValueExtractor
    {
        public FieldUrlExtractor(SPField field, MainDocumentPart mainDocumentPart)
        {
            Field = field;
            MainDocumentPart = mainDocumentPart;
        }

        public MainDocumentPart MainDocumentPart { get; set; }
        public SPField Field { get; set; }

        public string GetFieldValue(SPListItem item)
        {
            var fieldValue = item[Field.Id] as string;
            if (String.IsNullOrEmpty(fieldValue))
            {
                return String.Empty;
            }
            var fieldUrlValue = new SPFieldUrlValue(fieldValue);
            if (fieldUrlValue == null)
            {
                throw new WordExporterException("This is not a URL Field. Field  ----   " + Field.InternalName);
            }
            if (MainDocumentPart == null)
            {
                return fieldUrlValue.Url;
            }
            var uri = new Uri(fieldUrlValue.Url);
            var relationshipMatch = MainDocumentPart.HyperlinkRelationships.FirstOrDefault(rel => rel.Uri == uri) ??
                                    MainDocumentPart.AddHyperlinkRelationship(uri, true);
            var relationshipId = relationshipMatch.Id;
            var newParagraph = new Paragraph(
                new Hyperlink(
                    new ProofError {Type = ProofingErrorValues.GrammarStart},
                    new Run(
                        new RunProperties(new RunStyle {Val = "Hyperlink"}),
                        new Text(fieldUrlValue.Description)
                        )) {History = OnOffValue.FromBoolean(true), Id = relationshipId});
            return newParagraph.OuterXml;
        }
    }
}
